package jsyf.oa.service.weekplan;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.weekplan.WeekPlanDao;
import jsyf.oa.entity.weekplan.WeekPlanEntity;
import jsyf.oa.facade.weekplan.WeekPlanFacade;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by LT on 2018/3/19.
 */

@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class WeekPlanService implements WeekPlanFacade {
    @Autowired
    private WeekPlanDao weekPlanDao;

    @Override
    public String add(String jsonData) {
        List<WeekPlanEntity> entity = (List<WeekPlanEntity>) JSONArray.toCollection(JSONArray.fromObject(jsonData), WeekPlanEntity.class);
        for (int i = 0; i < entity.size(); i++) {
            WeekPlanEntity model = entity.get(i);
            weekPlanDao.add(model);
        }
        return "true";
    }

    @Override
    public JSONObject removeById(String jsonData) {
        JSONObject jsonObject = new JSONObject();
        if (weekPlanDao.removeById(JSON.parseObject(jsonData).getString("id")) > 0) {
            jsonObject.put("records", "删除成功");
        } else {
            jsonObject.put("records", "删除失败");
        }
        ;
        return jsonObject;
    }

    @Override
    public JSONObject update(String jsonData) {
        JSONObject jsonObject = new JSONObject();
        List<WeekPlanEntity> entity = (List<WeekPlanEntity>) JSONArray.toCollection(JSONArray.fromObject(jsonData), WeekPlanEntity.class);
        for (int i = 0; i < entity.size(); i++) {
            WeekPlanEntity model = entity.get(i);
            WeekPlanEntity oldEntity = (WeekPlanEntity) weekPlanDao.getIBaseEntityById(model.getId());
            if (model.getCustomerAddress() != null) {
                oldEntity.setCustomerAddress(model.getCustomerAddress());
            }
            if (model.getCustomerIndustry() != null) {
                oldEntity.setCustomerIndustry(model.getCustomerIndustry());
            }
            if (model.getIntentionDevice() != null) {
                oldEntity.setIntentionDevice(model.getIntentionDevice());
            }
            if (model.getLastVisitTime() != null) {
                oldEntity.setLastVisitTime(model.getLastVisitTime());
            }
            if (model.getRemake() != null) {
                oldEntity.setRemake(model.getRemake());
            }
            if (model.getWeekName() != null) {
                oldEntity.setWeekName(model.getWeekName());
            }
            if (model.getCustomerName() != null) {
                oldEntity.setCustomerName(model.getCustomerName());
            }
            if (model.getCreateUserId() != null) {
                oldEntity.setCreateUserId(model.getCreateUserId());
            }
            if (model.getId() != null) {
                oldEntity.setId(model.getId());
            }
            weekPlanDao.update(oldEntity);
        }
        jsonObject.put("records", "修改成功");
        return jsonObject;
    }

    public static String getFirstDayOfWeek(String date, int day) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        try {
            cal.setTime(sdf.parse(date));
            // Calendar默认周日为第一天, 所以设置为1
            cal.set(Calendar.DAY_OF_WEEK, day);
        } catch (Exception e) {

        }
        return sdf.format(cal.getTime());
    }

    @Override
    public JSONObject getWeek(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        JSONObject result = new JSONObject();
        StringBuffer weekCondition = new StringBuffer();
        String createUserId = jsonParams.getString("createUserId");
        String weekTime = jsonParams.getString("weekTime");
        String reportDate = jsonParams.getString("reportDate");
        String lastSun = null;
        String lastSat = null;
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String nowDate = sdf.format(date);
        if (!StringUtils.isBlank(reportDate)) {
            lastSun = getFirstDayOfWeek(reportDate, 1);
            lastSat = getFirstDayOfWeek(reportDate, 7);
        } else {
            lastSun = getFirstDayOfWeek(nowDate, 1);
            lastSat = getFirstDayOfWeek(nowDate, 7);
        }
        StringBuffer condition = new StringBuffer();
        if (!StringUtils.isBlank(createUserId) && StringUtils.isBlank(weekTime)) {
            condition.append(" AND CREATE_USER_ID=?\n");
            condition.append(" AND LEFT(WEEK_TIME,10) BETWEEN ? AND ?\n");
            condition.append(" ORDER BY WEEK_TIME ,CUSTOMER_INDUSTRY is not NULL desc  ");
            List<JSONObject> records = weekPlanDao.getJSONListByCondition(condition.toString(), new Object[]{createUserId, lastSun, lastSat});
            result.put("records", records);
        }
        if (!StringUtils.isBlank(createUserId) && !StringUtils.isBlank(weekTime)) {
            weekCondition.append(" AND CREATE_USER_ID=?\n");
            weekCondition.append(" AND LEFT(WEEK_TIME,10) BETWEEN ? AND ?\n");
            weekCondition.append(" AND WEEK_TIME=?");
            weekCondition.append(" ORDER BY WEEK_TIME ,CUSTOMER_INDUSTRY is not NULL desc  ");
            List<JSONObject> records = weekPlanDao.getJSONListByCondition(weekCondition.toString(), new Object[]{createUserId, lastSun, lastSat, weekTime});
            result.put("records", records);
        }

        return result;

    }

    @Override
    public JSONObject getWeekList(JSONObject jsonObject) {
        String companyId = jsonObject.getString("companyId");
        String userId = jsonObject.getString("userId");
        JSONObject o = new JSONObject();
        Map<String, Date> map = new HashMap<String, Date>();
        String lastSun = null;
        String lastSat = null;
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String nowDate = sdf.format(date);
        lastSun = getFirstDayOfWeek(nowDate, 1);
        lastSat = getFirstDayOfWeek(nowDate, 7);
        List<JSONObject> records = weekPlanDao.getDetail(userId, companyId, lastSun, lastSat);
        List<JSONObject> newrocrds = new ArrayList<JSONObject>();
        for (JSONObject jsonObject1 : records) {
            if (!"".equals(jsonObject1.getString("customerName")) || !"".equals(jsonObject1.getString("customerAddress"))) {
                newrocrds.add(jsonObject1);
            }
        }
        o.put("records", newrocrds);
        return o;
    }

    @Override
    public List<JSONObject> getCompanyList(JSONObject jSONObject) {
        String UserId = jSONObject.getString("userId");
        String roleName = jSONObject.getString("roleName");
        String companyId = jSONObject.getString("companyId");
        String reportDate = jSONObject.getString("reportDate");
        String lastSun = null;
        String lastSat = null;
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String nowDate = sdf.format(date);
        if (!StringUtils.isBlank(reportDate)) {
            lastSun = getFirstDayOfWeek(reportDate, 1);
            lastSat = getFirstDayOfWeek(reportDate, 7);
        } else {
            lastSun = getFirstDayOfWeek(nowDate, 1);
            lastSat = getFirstDayOfWeek(nowDate, 7);
        }
        if ("大客户支持".equals(roleName) || "大客户副总裁".equals(roleName)) {
            List<JSONObject> companyList = weekPlanDao.getCompanyList(roleName, UserId, lastSun, lastSat);
            List<JSONObject> totalList = weekPlanDao.getTotal(lastSun, lastSat);
            for (int j = 0; j < companyList.size(); j++) {
                for (int i = 0; i < totalList.size(); i++) {
                    if (companyList.get(j).getString("companyName").equals(totalList.get(i).getString("companyName"))) {
                        companyList.get(j).put("count", totalList.get(i).getString("count"));
                    }
                }
            }
            return companyList;
        }
        List<JSONObject> companyList = weekPlanDao.getSomeCompanyList(UserId, roleName, companyId, lastSun, lastSat);
        List<JSONObject> totalList = weekPlanDao.getTotal(lastSun, lastSat);
        for (int j = 0; j < companyList.size(); j++) {
            for (int i = 0; i < totalList.size(); i++) {
                if (companyList.get(j).getString("companyName").equals(totalList.get(i).getString("companyName"))) {
                    companyList.get(j).put("count", totalList.get(i).getString("count"));
                }
            }
        }
        return companyList;
    }

    @Override
    public List<JSONObject> getNameAndTel(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        StringBuffer weekCondition = new StringBuffer();
        String key = jsonParams.getString("key");
        String createUserId = jsonParams.getString("createUserId");
        if (!StringUtils.isBlank(key)) {
            weekCondition.append(" AND NAME LIKE ? ");
            weekCondition.append(" AND (ID in (SELECT CUSTOMER_ID FROM t_wrt_customer_visit WHERE CREATE_USER_ID = ?) OR CREATE_USER_ID=? OR CREATE_USER_ID in (SELECT\n" +
                    "\t\t\tUSER_ID\n" +
                    "\t\tFROM\n" +
                    "\t\t\tt_sys_user_2_region\n" +
                    "\t\tWHERE\n" +
                    "\t\t\tREGION_ID IN (\n" +
                    "\t\t\t\tSELECT\n" +
                    "\t\t\t\t\tREGION_ID\n" +
                    "\t\t\t\tFROM\n" +
                    "\t\t\t\t\tt_sys_user_2_region\n" +
                    "\t\t\t\tWHERE\n" +
                    "\t\t\t\t\tUSER_ID = ?\n" +
                    "\t\t\t))) ");
            List<JSONObject> records = weekPlanDao.getNameAndTel(weekCondition.toString(), new Object[]{"%" + key + "%", createUserId, createUserId,createUserId});
            return records;
        } else {
            return null;
        }
    }


}
